/**
 * 
 */
package org.mhz.ootw.util;

import org.apache.commons.lang.StringUtils;

/**
 * @author Mahan
 * 
 *         Ellipsis
 */
public final class Ellipsis
{
    /**
     * Private constructor
     */
    private Ellipsis()
    {
        
    }
    
    /**
     * Determine width of text
     *
     * @param aText - The text to check
     * @return The width of the text
     */
    private static int textWidth(final String aText)
    {
        if (StringUtils.isEmpty(aText))
        {
            return 0;
            
        }
        
        return (int) (aText.length() - aText.replaceAll(Constants.NON_THIN, "").length() / 2);
    }

    /**
     * Determine the ellipsis text
     *
     * @param aText - The text to convert into an ellipsis
     * @param aMaxDisplayLength - The maximum display length
     * @return The ellipsis text
     */
    public static String getShortenedText(final String aText, final int aMaxDisplayLength)
    {

        if (textWidth(aText) <= aMaxDisplayLength)
        {
            return aText;
        }

        // Start by chopping off at the word before max
        // This is an over-approximation due to thin-characters...
        int end = aText.lastIndexOf(' ', aMaxDisplayLength - Constants.ELLIPSIS_END_LENGTH);

        // Just one long word. Chop it off.
        if (end == -1)
        {
            return aText.substring(0, aMaxDisplayLength - Constants.ELLIPSIS_END_LENGTH) + Constants.ELLIPSIS_END;
        }

        // Step forward as long as textWidth allows.
        int newEnd = end;
        do
        {
            end = newEnd;
            newEnd = aText.indexOf(' ', end + 1);

            // No more spaces.
            if (newEnd == -1)
            {
                newEnd = aText.length();
            }

        }
        while (textWidth(aText.substring(0, newEnd) + Constants.ELLIPSIS_END) < aMaxDisplayLength);

        return aText.substring(0, end) + Constants.ELLIPSIS_END;
    }
    
    
    /**
     * Determine the ellipsis text with no highlighting
     *
     * @param aText - The text to convert into an ellipsis
     * @param aMaxDisplayLength - The maximum display length
     * @return The ellipsis text with no highlighting
     */
    public static String getShortenedTextNoHighlight(final String aText, final int aMaxDisplayLength)
    {
        String shortenedNoHighlight = getShortenedText(aText, aMaxDisplayLength);

        if (StringUtils.isNotBlank(shortenedNoHighlight))
        {
            shortenedNoHighlight = shortenedNoHighlight.replaceAll(Constants.HIGHLIGHT_START_TAG, "");
            shortenedNoHighlight = shortenedNoHighlight.replaceAll(Constants.HIGHLIGHT_END_TAG, "");
        }
        
        return shortenedNoHighlight;
    }
}
